﻿//using LinnerToolkit.Core.Mvvm;
//using SimulationPTSystem.DAL;
//using SimulationPTSystem.Evaluation.Enums;
//using System;
//using System.Collections.Generic;

//namespace SimulationPTSystem.Evaluation.Models
//{
//    public class Trainer : NotifyPropertyChanged
//    {
//        public ChengYuanInfo ChengYuanInfo { get; set; }

//        private bool wifi;
//        public bool Wifi { get => wifi; set => SetProperty(ref wifi,value); }

//        #region 求助信号
//        private bool raiseHand = false;
//        /// <summary>
//        /// 求助信号
//        /// </summary>
//        public bool RaiseHand { get => raiseHand; set => SetProperty(ref raiseHand, value); }
//        #endregion

//        #region 呼吸信号
//        private bool breatheSignal = false;
//        /// <summary>
//        /// 呼吸信号
//        /// </summary>
//        public bool BreatheSignal { get => breatheSignal; set => SetProperty(ref breatheSignal, value); }
//        #endregion

//        #region 脉搏信号
//        private bool pulseSignal = false;
//        /// <summary>
//        /// 脉搏信号
//        /// </summary>
//        public bool PulseSignal { get => pulseSignal; set => SetProperty(ref pulseSignal, value); }
//        #endregion

//        #region 传感器信号
//        private bool machineSignal = true;
//        /// <summary>
//        /// 传感器信号
//        /// </summary>
//        public bool MachineSignal { get => machineSignal; set => SetProperty(ref machineSignal, value); }

//        #region 换曲信号
//        private bool changeMusic = false;
//        /// <summary>
//        /// 换曲信号
//        /// </summary>
//        public bool ChangeMusic { get => changeMusic; set => SetProperty(ref changeMusic, value); }
//        #endregion

//            #region 训练时间

//            /// <summary>
//            /// 开始训练时间
//            /// </summary>
//        public TimeSpan StartTime { get; set; }
//        /// <summary>
//        /// 实际训练时间
//        /// </summary>
//        public TimeSpan ActualTrainingTime { get; set; }

//        #endregion

//        #region PNN50
//        private float pnn50 = 0f;
//        /// <summary>
//        /// PNN50
//        /// </summary>
//        public float PNN50 { get => pnn50; set => SetProperty(ref pnn50, value); }
//        #endregion

//            #region 心率变异性
//        private float hrv = 0;
//        /// <summary>
//        /// 心率变异性
//        /// </summary>
//        public float HRV { get => hrv; set => SetProperty(ref hrv, value); }
//        #endregion

//            /// <summary>
//            /// 训练得到的脉搏数据
//            /// </summary>
//        internal List<float> tempPulses = new List<float>();
//        private int pulseAve = 0;
//        /// <summary>
//        /// 脉搏均值
//        /// </summary>
//        public int PulseAve { get => pulseAve; set => SetProperty(ref pulseAve, value); }

//        /// <summary>
//        /// 训练得到的呼吸频率数据
//        /// </summary>
//        internal List<float> tempRespiratoryRates = new List<float>();
//        private int respiratoryRateAve = 0;
//        /// <summary>
//        /// 呼吸均值
//        /// </summary>
//        public int RespiratoryRateAve { get => respiratoryRateAve; set => SetProperty(ref respiratoryRateAve, value); }

//        #region 脉搏相关
//        private List<float> pulseCycles = new List<float>();  // 计算脉搏即时值队列
//        private List<float> pulses_Basic = new List<float>();
//        private int tempPulseID = 2;  // 每次传送过来的脉搏值最多8位有效，其余丢弃。从receivedData[8]开始计算
//        private int HID = 0;  // 实时脉搏ID号(1-100)
//        private float HP_value = 0f;  // 当前全部正H放松值总和，参数A
//        private float HN_value = 0f;  // 当前全部负H放松值总和，参数B
//        internal bool has_H_Basic = false;  // 是否采集到脉搏基值

//        /// <summary>
//        /// 接收到数据中不包含新的脉搏数据累计值
//        /// </summary>
//        private int pulseUnvariedCount = 0;

//        /// <summary>
//        /// 脉搏周期
//        /// </summary>
//        public int PulseCycle = 0;

//        private float pulse = 0;
//        /// <summary>
//        /// 脉搏即时值
//        /// </summary>
//        public float Pulse { get => pulse; set => SetProperty(ref pulse, value); }

//        private float h_value = 0f;
//        /// <summary>
//        /// 当前H放松指数（放松度）
//        /// </summary>
//        public float H_value { get => h_value; set => SetProperty(ref h_value, value); }

//        /// <summary>
//        /// 训练得到的H放松指数
//        /// </summary>
//        internal List<float> H_values = new List<float>();

//        private float pulse_Basic_Value = 0f;
//        /// <summary>
//        /// 脉搏基值
//        /// </summary>
//        public float Pulse_Basic_Value { get => pulse_Basic_Value; set => SetProperty(ref pulse_Basic_Value, value); }
//        #endregion

//            #region 呼吸相关
//            /// <summary>
//            /// 实时呼吸信号组数（1-100）
//            /// </summary>
//        private int BID = 0;
//        /// <summary>
//        /// 接收到数据中不包含新的呼吸数据累计值
//        /// </summary>
//        private int breatheUnvariedCount = 0;
//        /// <summary>
//        /// 是否采集到呼吸基值
//        /// </summary>
//        internal bool has_B_Basic = false;
//        /// <summary>
//        /// 呼吸得分计算ID，每4个计算一次
//        /// </summary>
//        private int BFID = 0;
//        /// <summary>
//        /// 呼吸变化得分
//        /// </summary>
//        private float[] BFC_fraction = new float[4];
//        /// <summary>
//        /// 吸呼比变化得分
//        /// </summary>
//        private float[] IERC_fraction = new float[4];
//        /// <summary>
//        /// 正的B放松值总和，参数C
//        /// </summary>
//        private float BRPV = 0f;
//        /// <summary>
//        /// 负的B放松值总和，参数D
//        /// </summary>
//        private float BRNV = 0f;
//        /// <summary>
//        /// 当前B放松值
//        /// </summary>
//        private float BRV = 0f;
//        /// <summary>
//        /// 每次传送过来的呼吸值最多有4位有效，其余丢弃。从receivedData[13]开始计算
//        /// </summary>
//        private int tempBreatheID = 11;
//        /// <summary>
//        /// 计算呼吸频率基值队列
//        /// </summary>
//        private List<float> respiratoryRates = new List<float>();
//        /// <summary>
//        /// 计算吸呼比基值队列
//        /// </summary>
//        private List<float> IERates = new List<float>();

//        /// <summary>
//        /// 呼吸周期
//        /// </summary>
//        public int BreatheCycle = 0;

//        /// <summary>
//        /// 呼吸频率即时值
//        /// </summary>
//        private float respiratoryRate = 0f;
//        /// <summary>
//        /// 呼吸频率即时值
//        /// </summary>
//        public float RespiratoryRate { get => respiratoryRate; set => SetProperty(ref respiratoryRate, value); }

//        /// <summary>
//        /// 吸呼比即时值
//        /// </summary>
//        private float ieRate = 0f;
//        /// <summary>
//        /// 吸呼比即时值
//        /// </summary>
//        public float IERate { get => ieRate; set => SetProperty(ref ieRate, value); }

//        private int inspiratoryTime;
//        /// <summary>
//        /// 吸气时间（单位ms）
//        /// </summary>
//        public int InspiratoryTime { get => inspiratoryTime; set => SetProperty(ref inspiratoryTime, value); }

//        private int expiratoryTime;
//        /// <summary>
//        /// 呼气时间（单位ms）
//        /// </summary>
//        public int ExpiratoryTime { get => expiratoryTime; set => SetProperty(ref expiratoryTime, value); }

//        /// <summary>
//        /// 当前B放松指数（专注度）
//        /// </summary>
//        private float br_value = 0f;
//        /// <summary>
//        /// 当前B放松指数（专注度）
//        /// </summary>
//        public float BR_value { get => br_value; set => SetProperty(ref br_value, value); }

//        private float respiratory_Basic_Value = 0f;
//        /// <summary>
//        /// 呼吸频率基值
//        /// </summary>
//        public float Respiratory_Basic_Value { get => respiratory_Basic_Value; set => SetProperty(ref respiratory_Basic_Value, value); }

//        private float ieRate_Basic_Value = 0f;
//        /// <summary>
//        /// 吸呼比基值
//        /// </summary>
//        public float IERate_Basic_Value { get => ieRate_Basic_Value; set => SetProperty(ref ieRate_Basic_Value, value); }
//        #endregion

//            #region 综合放松指数
//        private float c_value = 0;
//        /// <summary>
//        /// 综合放松指数
//        /// </summary>
//        public float C_value { get => c_value; set => SetProperty(ref c_value, value); }

//        /// <summary>
//        /// 综合放松指数数组
//        /// </summary>
//        public List<float> C_values = new List<float>();

//        private byte C_Value_Level = 0;

//        private float c_ValueAveInOneMinute;
//        public float C_ValueAveInOneMinute { get => c_ValueAveInOneMinute; set => SetProperty(ref c_ValueAveInOneMinute, value); }
//        #endregion

//            /// <summary>
//            /// 脉搏、呼吸频率、吸呼比、H、B、C放松指数的基值、前中后总均值、标准差、参考范围
//            /// </summary>
//        public float[][] reportData = new float[6][];

//        // 呼吸得分S与吸呼比得分X对应表
//        private static double[,] BFC_Table = new double[,]{
//        {-10000,-7,-8},{-7,-3,-4},{-3,-1.5,-2},{-1.5,-1,-1},
//        {-1,1,0},{1,1.5,1},{1.5,4,2},{4,9,4},{9,10000,8}};
//        private static double[,] IERC_Table = new double[,] {
//        { -10000, -0.2, 8 }, { -0.2, -0.15, 4 }, { -0.15, -0.06, 2 }, { -0.06, -0.03, 1 },
//        { -0.03, 0.03, 0 }, { 0.03, 0.06, 1 }, { 0.06, 0.15, 2 }, { 0.15, 0.2, 4 }, { 0.2, 10000, 8 } };

//        public TrainingState TrainingState = TrainingState.NotStart;

//        internal byte[] sendData = new byte[8];

//        /// <summary>
//        /// 获得脉搏、呼吸基值的时间
//        /// </summary>
//        protected TimeSpan Basic_Value_Time;

//        /// <summary>
//        /// 最近一分钟内储存的综合放松指数值
//        /// </summary>
//        protected List<float> tempC_Values = new List<float>();

//        /// <summary>
//        /// 终端是否处于MP3状态
//        /// </summary>
//        internal bool IsMP3State = true;
//        /// <summary>
//        /// 吸气标志
//        /// </summary>
//        public bool IsInHale = false;

//        /// <summary>
//        /// 专注度小于零的个数
//        /// </summary>
//        protected int countOfBRNV = 0;

//        /// <summary>
//        /// 专注度连续小于0的个数
//        /// </summary>
//        protected int consecutiveCountOfBRNV = 0;

//        /// <summary>
//        /// 主播放器是否已经播放过指导语等
//        /// </summary>
//        protected bool HasAPlayerWorked = false;
//        /// <summary>
//        /// A播放器是否正在播放曲目
//        /// </summary>
//        public bool IsAPlayerWork { get => isAPlayerWork; set => SetProperty(ref isAPlayerWork, value); }
//        private bool isAPlayerWork = false;
//        /// <summary>
//        /// B播放器是否正在播放曲目
//        /// </summary>
//        public bool IsBPlayerWork { get => isBPlayerWork; set => SetProperty(ref isBPlayerWork, value); }
//        private bool isBPlayerWork = false;

//        /// <summary>
//        /// 主播放器，负责播放指导语和背景音
//        /// </summary>
//        protected byte APlayer = 0x01;
//        /// <summary>
//        /// 辅助播放器，负责播放背景音乐（智能换曲）
//        /// </summary>
//        protected byte BPlayer = 0x02;
//        /// <summary>
//        /// 辅助播放器曲目列表
//        /// </summary>
//        protected List<byte> listChangedMusic = new List<byte>();
//        /// <summary>
//        /// 辅助播放器临时曲目列表
//        /// </summary>
//        protected List<byte> tempListChangedMusic = new List<byte>();
//        /// <summary>
//        /// 主播放器曲目列表
//        /// </summary>
//        protected List<byte> listMajorPlayerMusic = new List<byte>();
//        /// <summary>
//        /// 主播放器临时曲目列表
//        /// </summary>
//        protected List<byte> tempListMajorPlayerMusic = new List<byte>();
//        /// <summary>
//        /// 主播放器歌曲编号
//        /// </summary>
//        protected byte kindOfMajorMusic = 0x00;
//        /// <summary>
//        /// 辅助播放器歌曲类别
//        /// </summary>
//        protected byte kindOfChangedMusic = 0x00;

//        /// <summary>
//        /// 智能换曲次数
//        /// </summary>
//        public int CountOfChangeMusic
//        {
//            get;
//            set;
//        }

//        /// <summary>
//        /// 训练得到的吸呼比数据
//        /// </summary>
//        internal List<float> tempIERates = new List<float>();
//        /// <summary>
//        /// 训练得到的B放松指数
//        /// </summary>
//        internal List<float> B_values = new List<float>();

//        /// <summary>
//        /// 最持久放松奖下限(60)
//        /// </summary>
//        private static int CJFSLevel = 60;
//        /// <summary>
//        /// 最迅速放松奖下限(30)
//        /// </summary>
//        private static int XSFSLevel = 30;
//        /// <summary>
//        /// 最投入训练奖下限(40)
//        /// </summary>
//        private static int TRXLLevel = 40;
//        /// <summary>
//        /// H放松指数最大值
//        /// </summary>
//        public float Max_H_Value = 0f;
//        /// <summary>
//        /// H放松指数最小值
//        /// </summary>
//        public float Min_H_Value = 0f;
//        /// <summary>
//        /// B放松指数最大值
//        /// </summary>
//        public float Max_B_Value = 0f;
//        /// <summary>
//        /// B放松指数最小值
//        /// </summary>
//        public float Min_B_Value = 0f;
//        /// <summary>
//        /// 综合放松指数最大值
//        /// </summary>
//        public float Max_C_Value = 0f;
//        /// <summary>
//        /// 综合放松指数最小值
//        /// </summary>
//        public float Min_C_Value = 0;
//        /// <summary>
//        /// 最后一个综合放松指数
//        /// </summary>
//        public float End_C_Value = 0f;
//        /// <summary>
//        /// 持久放松累计时间
//        /// </summary>
//        public int CJFSDurationTime = 0;
//        /// <summary>
//        /// 综合放松指数第一次达到30%以上时的时间
//        /// </summary>
//        public int XSFSTime = 0;
//        /// <summary>
//        /// 投入训练持续时间缓冲值，用来和投入训练持续时间比较
//        /// </summary>
//        internal int tempTRXLDurationTime = 0;
//        /// <summary>
//        /// 投入训练持续时间
//        /// </summary>
//        public int TRXLDurationTime = 0;

//        private bool isMachineWork = false;
//        private int countOfMachineNotWork = 0;
//        bool isBreatheWork = true;
//        int GetBasicValue_Time = 0;

//        private int UselessDataCount = 0;

//        public Trainer(ChengYuanInfo chengYuanInfo)
//        {
//            ChengYuanInfo = chengYuanInfo;

//            sendData[0] = 0xAA;
//            sendData[1] = (byte)ChengYuanInfo.SensorDeviceID;
//            sendData[2] = 0x00;
//            sendData[3] = 0x00;
//            sendData[4] = 0x00;
//            sendData[5] = 0x00;
//            sendData[6] = 0x00;
//            sendData[7] = 0xFF;

//            for (int i = 0; i < reportData.Length; i++)
//            {
//                reportData[i] = new float[7];
//            }
//        }

//        /// <summary>
//        /// 接收数据并处理
//        /// </summary>
//        /// <param name="_receivedData"></param>
//        public void GetData(byte[] _receivedData)
//        {
//            if (!isMachineWork)
//            {
//                isMachineWork = true;
//                countOfMachineNotWork = 0;
//                if (!MachineSignal)
//                    MachineSignal = true;
//            }
//            DealData(_receivedData);
//        }

//        /// <summary>
//        /// 处理收到的数据
//        /// </summary>
//        /// <param name="anyone"></param>
//        public void DealData(byte[] receivedData)
//        {
//            // A、B播放器是否正在播放曲目,MP3状态及呼叫信号
//            char[] receivedChars = Convert.ToString(receivedData[18], 2).PadLeft(8, '0').ToCharArray();
//            if (receivedChars[7].Equals('1'))
//            {
//                if (!IsAPlayerWork)
//                    IsAPlayerWork = true;
//            }
//            else
//            {
//                if (IsAPlayerWork)
//                    IsAPlayerWork = false;
//            }
//            if (receivedChars[6].Equals('1'))
//            {
//                if (!IsBPlayerWork)
//                    IsBPlayerWork = true;
//            }
//            else
//            {
//                if (IsBPlayerWork)
//                {
//                    IsBPlayerWork = false;
//                }
//            }

//            if (receivedChars[5].Equals('1'))
//            {
//                if (!IsMP3State)
//                    IsMP3State = true;
//            }
//            else
//            {
//                if (IsMP3State)
//                {
//                    IsMP3State = false;
//                }
//            }
//            // NotStart=0 Started=1
//            if (((int)TrainingState) < 2)
//            {
//                // 呼叫信号
//                if (receivedChars[4].Equals('1'))
//                {
//                    if (!RaiseHand)
//                        RaiseHand = true;
//                }
//                else
//                {
//                    if (RaiseHand)
//                        RaiseHand = false;
//                }

//                // 滤值30次
//                if (UselessDataCount < 10)
//                {
//                    UselessDataCount++;
//                    return;
//                }

//                // 脉搏信号是否异常
//                if (receivedData[15] == 0x01)
//                {
//                    if (PulseErrorState == ErrorState.Interrupt)  // 正处于异常或中断状态，则返回正常状态
//                    {
//                        PulseErrorState = ErrorState.None;
//                        pulseUnvariedCount = 0;
//                        if (!PulseSignal)
//                            PulseSignal = true;
//                        if (BreatheErrorState == ErrorState.None)
//                        {
//                            disturbEndTime = Team.Controller.CurrentTime;
//                            DisturbTime = DisturbTime.Add(disturbEndTime.Subtract(disturbBeginTime));
//                        }
//                    }
//                }
//                else
//                {
//                    if (pulseUnvariedCount == 0)  // 若处于正常状态，则检测是否进入异常状态
//                    {
//                        pulseUnvariedCount = 5;
//                    }
//                }

//                if (receivedData[19] >= 0x80)
//                {
//                    if (!IsInHale)
//                        IsInHale = true;
//                }

//                else
//                {
//                    if (IsInHale)
//                        IsInHale = false;
//                }

//                GetPulse(receivedData);

//                GetBreathe(receivedData);
//            }
//        }
//    }
//}






using SimulationPTSystem.DAL;
using SimulationPTSystem.Evaluation.Codec;
using SimulationPTSystem.Evaluation.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;

namespace SimulationPTSystem.Evaluation.Models
{
    public class Trainer : INotifyPropertyChanged
    {
        /// <summary>
        /// 成员信息
        /// </summary>
        public ChengYuanInfo ChengYuanInfo { get; set; }

        #region 团体信息
        /// <summary>
        /// 所属团体
        /// </summary>
        public TeamInfo TeamInfo { get; set; }

        #endregion

        #region WIFI信号
        private bool wifi = false;
        /// <summary>
        /// WIFI信号
        /// </summary>
        public bool WIFI
        {
            get { return this.wifi; }
            set
            {
                this.wifi = value;
                NotifyPropertyChanged("WIFI");
            }
        }
        #endregion

        #region 求助信号
        private bool raiseHand = false;
        /// <summary>
        /// 求助信号
        /// </summary>
        public bool RaiseHand
        {
            get { return this.raiseHand; }
            set
            {
                this.raiseHand = value;
                NotifyPropertyChanged("RaiseHand");
            }
        }
        #endregion

        #region 呼吸信号
        private bool breatheSignal = false;
        /// <summary>
        /// 呼吸信号
        /// </summary>
        public bool BreatheSignal
        {
            get { return this.breatheSignal; }
            set
            {
                this.breatheSignal = value;
                NotifyPropertyChanged("BreatheSignal");
            }
        }
        #endregion

        #region 脉搏信号
        private bool pulseSignal = false;
        /// <summary>
        /// 脉搏信号
        /// </summary>
        public bool PulseSignal
        {
            get { return this.pulseSignal; }
            set
            {
                this.pulseSignal = value;
                NotifyPropertyChanged("PulseSignal");
            }
        }
        #endregion

        #region 传感器信号
        private bool machineSignal = true;
        /// <summary>
        /// 传感器信号
        /// </summary>
        public bool MachineSignal
        {
            get { return this.machineSignal; }
            set
            {
                this.machineSignal = value;
                NotifyPropertyChanged("MachineSignal");
            }
        }
        #endregion

        #region PNN50
        private float pnn50 = 0f;
        /// <summary>
        /// PNN50
        /// </summary>
        public float PNN50
        {
            get { return this.pnn50; }
            set
            {
                this.pnn50 = value;
                NotifyPropertyChanged("PNN50");
            }
        }
        #endregion

        #region 心率变异性
        private float hrv = 0;
        /// <summary>
        /// 心率变异性
        /// </summary>
        public float HRV
        {
            get { return this.hrv; }
            set
            {
                this.hrv = value;
                NotifyPropertyChanged("HRV");
            }
        }
        #endregion

        /// <summary>
        /// 训练得到的脉搏数据
        /// </summary>
        internal List<float> tempPulses = new List<float>();
        private int pulseAve = 0;
        /// <summary>
        /// 脉搏均值
        /// </summary>
        public int PulseAve
        {
            get { return pulseAve; }
            set
            {
                pulseAve = value;
                NotifyPropertyChanged("PulseAve");
            }
        }

        /// <summary>
        /// 训练得到的呼吸频率数据
        /// </summary>
        internal List<float> tempRespiratoryRates = new List<float>();
        private int respiratoryRateAve = 0;
        /// <summary>
        /// 呼吸均值
        /// </summary>
        public int RespiratoryRateAve
        {
            get { return respiratoryRateAve; }
            set
            {
                respiratoryRateAve = value;
                NotifyPropertyChanged("RespiratoryRateAve");
            }
        }

        #region 脉搏相关
        private List<float> pulseCycles = new List<float>();  // 计算脉搏即时值队列
        private List<float> pulses_Basic = new List<float>();
        private int tempPulseID = 2;  // 每次传送过来的脉搏值最多8位有效，其余丢弃。从receivedData[8]开始计算
        private int HID = 0;  // 实时脉搏ID号(1-100)
        private float HP_value = 0f;  // 当前全部正H放松值总和，参数A
        private float HN_value = 0f;  // 当前全部负H放松值总和，参数B
        internal bool has_H_Basic = false;  // 是否采集到脉搏基值

        /// <summary>
        /// 接收到数据中不包含新的脉搏数据累计值
        /// </summary>
        private int pulseUnvariedCount = 0;

        /// <summary>
        /// 脉搏周期
        /// </summary>
        public int PulseCycle = 0;

        private float pulse = 0;
        /// <summary>
        /// 脉搏即时值
        /// </summary>
        public float Pulse
        {
            get { return this.pulse; }
            set
            {
                this.pulse = value;
                NotifyPropertyChanged("Pulse");
            }
        }

        private float h_value = 0f;
        /// <summary>
        /// 当前H放松指数（放松度）
        /// </summary>
        public float H_value
        {
            get { return this.h_value; }
            set
            {
                this.h_value = value;
                NotifyPropertyChanged("H_value");
            }
        }

        /// <summary>
        /// 训练得到的H放松指数
        /// </summary>
        internal List<float> H_values = new List<float>();

        private float pulse_Basic_Value = 0f;
        /// <summary>
        /// 脉搏基值
        /// </summary>
        public float Pulse_Basic_Value
        {
            get { return this.pulse_Basic_Value; }
            set
            {
                this.pulse_Basic_Value = value;
                NotifyPropertyChanged("Pulse_Basic_Value");
            }
        }
        #endregion

        #region 呼吸相关
        /// <summary>
        /// 实时呼吸信号组数（1-100）
        /// </summary>
        private int BID = 0;
        /// <summary>
        /// 接收到数据中不包含新的呼吸数据累计值
        /// </summary>
        private int breatheUnvariedCount = 0;
        /// <summary>
        /// 是否采集到呼吸基值
        /// </summary>
        internal bool has_B_Basic = false;
        /// <summary>
        /// 呼吸得分计算ID，每4个计算一次
        /// </summary>
        private int BFID = 0;
        /// <summary>
        /// 呼吸变化得分
        /// </summary>
        private float[] BFC_fraction = new float[4];
        /// <summary>
        /// 吸呼比变化得分
        /// </summary>
        private float[] IERC_fraction = new float[4];
        /// <summary>
        /// 正的B放松值总和，参数C
        /// </summary>
        private float BRPV = 0f;
        /// <summary>
        /// 负的B放松值总和，参数D
        /// </summary>
        private float BRNV = 0f;
        /// <summary>
        /// 当前B放松值
        /// </summary>
        private float BRV = 0f;
        /// <summary>
        /// 每次传送过来的呼吸值最多有4位有效，其余丢弃。从receivedData[13]开始计算
        /// </summary>
        private int tempBreatheID = 11;
        /// <summary>
        /// 计算呼吸频率基值队列
        /// </summary>
        private List<float> respiratoryRates = new List<float>();
        /// <summary>
        /// 计算吸呼比基值队列
        /// </summary>
        private List<float> IERates = new List<float>();

        /// <summary>
        /// 呼吸周期
        /// </summary>
        public int BreatheCycle = 0;

        /// <summary>
        /// 呼吸频率即时值
        /// </summary>
        private float respiratoryRate = 0f;
        /// <summary>
        /// 呼吸频率即时值
        /// </summary>
        public float RespiratoryRate
        {
            get { return this.respiratoryRate; }
            set
            {
                this.respiratoryRate = value;
                NotifyPropertyChanged("RespiratoryRate");
            }
        }

        /// <summary>
        /// 吸呼比即时值
        /// </summary>
        private float ieRate = 0f;
        /// <summary>
        /// 吸呼比即时值
        /// </summary>
        public float IERate
        {
            get { return this.ieRate; }
            set
            {
                this.ieRate = value;
                NotifyPropertyChanged("IERate");
            }
        }

        private int inspiratoryTime;
        /// <summary>
        /// 吸气时间（单位ms）
        /// </summary>
        public int InspiratoryTime
        {
            get { return this.inspiratoryTime; }
            set
            {
                this.inspiratoryTime = value;
                NotifyPropertyChanged("InspiratoryTime");
            }
        }

        private int expiratoryTime;
        /// <summary>
        /// 呼气时间（单位ms）
        /// </summary>
        public int ExpiratoryTime
        {
            get { return this.expiratoryTime; }
            set
            {
                this.expiratoryTime = value;
                NotifyPropertyChanged("ExpiratoryTime");
            }
        }

        /// <summary>
        /// 当前B放松指数（专注度）
        /// </summary>
        private float br_value = 0f;
        /// <summary>
        /// 当前B放松指数（专注度）
        /// </summary>
        public float BR_value
        {
            get { return this.br_value; }
            set
            {
                this.br_value = value;
                NotifyPropertyChanged("BR_value");
            }
        }

        private float respiratory_Basic_Value = 0f;
        /// <summary>
        /// 呼吸频率基值
        /// </summary>
        public float Respiratory_Basic_Value
        {
            get { return this.respiratory_Basic_Value; }
            set
            {
                this.respiratory_Basic_Value = value;
                NotifyPropertyChanged("Respiratory_Basic_Value");
            }
        }

        private float ieRate_Basic_Value = 0f;
        /// <summary>
        /// 吸呼比基值
        /// </summary>
        public float IERate_Basic_Value
        {
            get { return this.ieRate_Basic_Value; }
            set
            {
                this.ieRate_Basic_Value = value;
                NotifyPropertyChanged("IERate_Basic_Value");
            }
        }
        #endregion

        #region 综合放松指数
        private float c_value = 0;
        /// <summary>
        /// 综合放松指数
        /// </summary>
        public float C_value
        {
            get { return this.c_value; }
            set
            {
                this.c_value = value;
                NotifyPropertyChanged("C_value");
            }
        }

        /// <summary>
        /// 综合放松指数数组
        /// </summary>
        public List<float> C_values = new List<float>();

        private byte C_Value_Level = 0;

        private float c_ValueAveInOneMinute;
        public float C_ValueAveInOneMinute
        {
            get { return this.c_ValueAveInOneMinute; }
            set
            {
                this.c_ValueAveInOneMinute = value;
                NotifyPropertyChanged("C_ValueAveInOneMinute");
            }
        }
        #endregion

        /// <summary>
        /// 脉搏、呼吸频率、吸呼比、H、B、C放松指数的基值、前中后总均值、标准差、参考范围
        /// </summary>
        public float[][] reportData = new float[6][];

        // 呼吸得分S与吸呼比得分X对应表
        private static double[,] BFC_Table = new double[,]{
        {-10000,-7,-8},{-7,-3,-4},{-3,-1.5,-2},{-1.5,-1,-1},
        {-1,1,0},{1,1.5,1},{1.5,4,2},{4,9,4},{9,10000,8}};
        private static double[,] IERC_Table = new double[,] {
        { -10000, -0.2, 8 }, { -0.2, -0.15, 4 }, { -0.15, -0.06, 2 }, { -0.06, -0.03, 1 },
        { -0.03, 0.03, 0 }, { 0.03, 0.06, 1 }, { 0.06, 0.15, 2 }, { 0.15, 0.2, 4 }, { 0.2, 10000, 8 } };

        public TrainingState TrainingState = TrainingState.NotStart;

        internal byte[] sendData = new byte[8];

        /// <summary>
        /// 最近一分钟内储存的综合放松指数值
        /// </summary>
        protected List<float> tempC_Values = new List<float>();

        /// <summary>
        /// 终端是否处于MP3状态
        /// </summary>
        internal bool IsMP3State = true;
        /// <summary>
        /// 吸气标志
        /// </summary>
        public bool IsInHale = false;

        /// <summary>
        /// 专注度小于零的个数
        /// </summary>
        protected int countOfBRNV = 0;

        /// <summary>
        /// 专注度连续小于0的个数
        /// </summary>
        protected int consecutiveCountOfBRNV = 0;

        /// <summary>
        /// 训练得到的吸呼比数据
        /// </summary>
        internal List<float> tempIERates = new List<float>();
        /// <summary>
        /// 训练得到的B放松指数
        /// </summary>
        internal List<float> B_values = new List<float>();

        /// <summary>
        /// 最持久放松奖下限(60)
        /// </summary>
        private static int CJFSLevel = 60;
        /// <summary>
        /// 最迅速放松奖下限(30)
        /// </summary>
        private static int XSFSLevel = 30;
        /// <summary>
        /// 最投入训练奖下限(40)
        /// </summary>
        private static int TRXLLevel = 40;
        /// <summary>
        /// H放松指数最大值
        /// </summary>
        public float Max_H_Value = 0f;
        /// <summary>
        /// H放松指数最小值
        /// </summary>
        public float Min_H_Value = 0f;
        /// <summary>
        /// B放松指数最大值
        /// </summary>
        public float Max_B_Value = 0f;
        /// <summary>
        /// B放松指数最小值
        /// </summary>
        public float Min_B_Value = 0f;
        /// <summary>
        /// 综合放松指数最大值
        /// </summary>
        public float Max_C_Value = 0f;
        /// <summary>
        /// 综合放松指数最小值
        /// </summary>
        public float Min_C_Value = 0;
        /// <summary>
        /// 最后一个综合放松指数
        /// </summary>
        public float End_C_Value = 0f;
        /// <summary>
        /// 持久放松累计时间
        /// </summary>
        public int CJFSDurationTime = 0;
        /// <summary>
        /// 综合放松指数第一次达到30%以上时的时间
        /// </summary>
        public int XSFSTime = 0;
        /// <summary>
        /// 投入训练持续时间缓冲值，用来和投入训练持续时间比较
        /// </summary>
        internal int tempTRXLDurationTime = 0;
        /// <summary>
        /// 投入训练持续时间
        /// </summary>
        public int TRXLDurationTime = 0;

        public Trainer(ChengYuanInfo chengYuanInfo)
        {
            ChengYuanInfo = chengYuanInfo;

            InitializeComponents();
        }

        private void InitializeComponents()
        {
            sendData[0] = 0xAA;
            sendData[1] = (byte)ChengYuanInfo.SensorDeviceID;
            sendData[2] = 0x00;
            sendData[3] = 0x00;
            sendData[4] = 0x00;
            sendData[5] = 0x00;
            sendData[6] = 0x00;
            sendData[7] = 0xFF;

            for (int i = 0; i < reportData.Length; i++)
            {
                reportData[i] = new float[7];
            }
        }

        /// <summary>
        /// 接收数据并处理
        /// </summary>
        public void GetData(SensorData sensorData,TimeSpan time )
        {
            if (!isMachineWork)
            {
                isMachineWork = true;
                countOfMachineNotWork = 0;
                if (!MachineSignal)
                {
                    MachineSignal = true;
                }
            }
            DealData(sensorData, time);
        }

        private int UselessDataCount = 0;

        /// <summary>
        /// 处理收到的数据
        /// </summary>
        /// <param name="anyone"></param>
        public void DealData(SensorData sensorData,TimeSpan time)
        {
            // A、B播放器是否正在播放曲目,MP3状态及呼叫信号
            IsMP3State = sensorData.IsMP3State;

            if (((int)TrainingState) < 2)
            {
                RaiseHand = sensorData.RaiseHand;

                // 滤值1次
                if (UselessDataCount < 1)
                {
                    UselessDataCount++;
                    return;
                }

                // 脉搏信号是否异常
                if (sensorData.PulseState== PulseState.Normal)
                {
                    if (PulseErrorState == ErrorState.Interrupt)  // 正处于异常或中断状态，则返回正常状态
                    {
                        PulseErrorState = ErrorState.None;
                        pulseUnvariedCount = 0;
                        if (!PulseSignal)
                            PulseSignal = true;
                    }
                }
                else
                {
                    if (pulseUnvariedCount == 0)  // 若处于正常状态，则检测是否进入异常状态
                    {
                        pulseUnvariedCount = 5;
                    }
                }

                IsInHale = sensorData.IsInHale;

                GetPulse(sensorData,time);

                GetBreathe(sensorData, time);
            }
        }

        private ErrorState pulseErrorState = ErrorState.None;
        /// <summary>
        /// 脉搏出错状态
        /// </summary>
        public ErrorState PulseErrorState
        {
            get { return this.pulseErrorState; }
            set
            {
                this.pulseErrorState = value;
                NotifyPropertyChanged("PulseErrorState");
            }
        }
        private ErrorState breatheErrorState = ErrorState.None;
        /// <summary>
        /// 呼吸出错状态
        /// </summary>
        public ErrorState BreatheErrorState
        {
            get { return this.breatheErrorState; }
            set
            {
                this.breatheErrorState = value;
                NotifyPropertyChanged("BreatheErrorState");
            }
        }

        /// <summary>
        /// 取到初标后数组里已存在的值
        /// </summary>
        private int CBCount = 0;
        /// <summary>
        /// 计算脉搏即时值
        /// </summary>
        private void GetPulse(SensorData sensorData,TimeSpan time)
        {
            HID = sensorData.HID;

            // 若有新的脉搏数据
            if (sensorData.PulseCycles.Count > 0)
            {
                if (PulseErrorState == ErrorState.None && !PulseSignal)
                {
                    PulseSignal = true;
                }
                if (PulseErrorState == ErrorState.Interrupt)
                {
                    PulseErrorState = ErrorState.None;
                    pulseUnvariedCount = 0;
                    if (!PulseSignal)
                        PulseSignal = true;
                }

                for (int i = 0; i < sensorData.PulseCycles.Count; i++)
                {
                    PulseCycle = sensorData.PulseCycles[i];
                    // 判断是否有初标
                    if (_minPulseCycle > 0)
                    {
                        // 若脉搏周期小于有效脉搏周期下限（即脉搏值大于有效脉搏最大值）
                        if (PulseCycle < _minPulseCycle)
                        {
                            // 若脉搏周期小于异常脉搏周期下限（即脉搏值大于异常脉搏最大值）
                            if (PulseCycle < _minAbnormityPulseCycle)
                            {
                                if (_minAbnormityPulseCycleCount < 6)
                                {
                                    _minAbnormityPulseCycleCount++;
                                    if (_minAbnormityPulseCycleCount >= 6)
                                    {
                                        PulseErrorState = ErrorState.Disturb;
                                        if (PulseSignal)
                                            PulseSignal = false;
                                    }
                                }
                            }
                            PulseCycle = _minPulseCycle;
                        }
                        else
                        {
                            // 若处于干扰状态，则进入正常状态
                            if (PulseErrorState == ErrorState.Disturb)
                            {
                                PulseErrorState = ErrorState.None;
                                _minAbnormityPulseCycleCount = 0;
                                if (!PulseSignal)
                                    PulseSignal = true;
                            }
                            // 若脉搏周期大于有效脉搏周期上限（即脉搏值小于有效脉搏最小值）
                            if (PulseCycle > _maxPulseCycle)
                            {
                                PulseCycle = _maxPulseCycle;
                            }
                        }
                    }
                    pulseCycles.Add(PulseCycle);
                }

                // 只保留最新数据，其余移除
                if (pulseCycles.Count > 20)
                {
                    pulseCycles.RemoveRange(0, pulseCycles.Count - 20);
                }

                // 更新H_value或将Pulse值加入计算H_value基值队列
                if (pulseCycles.Count > 0)
                {
                    // 计算出脉搏即时值
                    /*
                    float tempPulse = 60000 / (pulseCycles.Average());
                     */
                    Pulse = 60000 / (pulseCycles.Average());
                    tempPulses.Add(Pulse);
                    // 脉搏均值
                    PulseAve = (int)tempPulses.Average();
                    //PulseAve = (int)((PulseAve * (tempPulses.Count - 1) + tempPulses[tempPulses.Count - 1]) / tempPulses.Count);

                    // 计算HRV
                    if (tempPulses.Count > 1)
                    {
                        HRV = PulseCycle - (pulseCycles[pulseCycles.Count - 2]);
                        if (HRV > 50)
                        {
                            PNN50 = ((float)(PNN50 * (tempPulses.Count - 2)) + 1) / (tempPulses.Count - 1);
                        }
                        else
                        {
                            PNN50 = (float)(PNN50 * (tempPulses.Count - 2)) / (tempPulses.Count - 1);
                        }
                    }
                    DealPulse();

                    if (has_H_Basic && has_B_Basic)
                    {
                        Update_H_value(Pulse);
                    }
                    // 若脉搏即时值有效且无脉搏基值，则将脉搏即时值加入脉搏计算队列
                    else if (!has_H_Basic)
                    {
                        pulses_Basic.Add(Pulse);
                        // 若没取到初标
                        if (_maxPulseCycle > 0)
                        {
                            if (pulses_Basic.Count == 10)
                            {
                                CBCount = GetAverageData(pulses_Basic);
                            }
                        }
                        if (pulses_Basic.Count >= (CBCount + 20) && respiratoryRates.Count >= 4)
                        {
                            if (GetBasicValue_Time >= 60000)
                            {
                                GetBasicValue();
                            }
                        }
                    }
                }
            }
            else
            {
                if (pulseUnvariedCount >= 5 && pulseUnvariedCount < 40)
                {
                    pulseUnvariedCount++;
                    if (pulseUnvariedCount == 10)
                    {
                        if (PulseErrorState == ErrorState.Disturb)
                        {
                            _minAbnormityPulseCycleCount = 0;
                        }
                    }
                    else if (pulseUnvariedCount == 40)
                    {
                        if (PulseSignal)
                            PulseSignal = false;
                        PulseErrorState = ErrorState.Interrupt;
                    }
                }
            }
        }

        protected  void DealPulse() { }

        private TimeSpan disturbTime = new TimeSpan();
        /// <summary>
        /// 训练中受干扰的时间
        /// </summary>
        public TimeSpan DisturbTime
        {
            get { return this.disturbTime; }
            set
            {
                this.disturbTime = value;
                NotifyPropertyChanged("DisturbTime");
            }
        }
        private TimeSpan disturbBeginTime = new TimeSpan();
        private TimeSpan disturbEndTime = new TimeSpan();

        /// <summary>
        /// 计算呼吸即时值
        /// </summary>
        private void GetBreathe(SensorData sensorData,TimeSpan time)
        {
            BID = sensorData.BID;

            // 如果有新的呼吸数据
            if (sensorData.InspiratoryTimes.Count > 0 && sensorData.ExpiratoryTimes.Count > 0 && sensorData.InspiratoryTimes.Count.Equals(sensorData.ExpiratoryTimes.Count))
            {
                if (!isBreatheWork)
                {
                    isBreatheWork = true;
                    if (breatheUnvariedCount > 0)
                        breatheUnvariedCount = 0;
                    if (BreatheErrorState == ErrorState.Interrupt)
                    {
                        BreatheErrorState = ErrorState.None;
                        if (!BreatheSignal)
                            BreatheSignal = true;
                    }
                }
                if (BreatheErrorState == ErrorState.None && !BreatheSignal)
                {
                    BreatheSignal = true;
                }

                for (int i = 0; i < sensorData.InspiratoryTimes.Count; i++)
                {
                    BreatheCycle = sensorData.InspiratoryTimes[i] + sensorData.ExpiratoryTimes[i];
                    float tempRespiratoryRate = (float)(1200 / BreatheCycle);
                    // 判断是否取过基值
                    if (_maxAbnormityRepiratory > 0)
                    {
                        // 若呼吸频率值大于异常呼吸频率最大值
                        if (tempRespiratoryRate > _maxAbnormityRepiratory)
                        {
                            if (_maxAbnormityRespiratoryCount < 6)
                            {
                                _maxAbnormityRespiratoryCount++;
                                if (_maxAbnormityRespiratoryCount >= 6)
                                {
                                    BreatheErrorState = ErrorState.Disturb;
                                    if (BreatheSignal)
                                    {
                                        BreatheSignal = false;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (BreatheErrorState == ErrorState.Disturb)
                            {
                                BreatheErrorState = ErrorState.None;
                                _maxAbnormityRespiratoryCount = 0;
                                if (!BreatheSignal)
                                {
                                    BreatheSignal = true;
                                }
                            }
                        }
                    }
                    RespiratoryRate = tempRespiratoryRate > 45 ? 45 : tempRespiratoryRate;
                    tempRespiratoryRate = (float)((float)sensorData.InspiratoryTimes[i] / (float)sensorData.ExpiratoryTimes[i]);
                    if (tempRespiratoryRate < 0.1f)
                    {
                        float tempOffset = tempRespiratoryRate / 0.1f;
                        IERate = 0.1f;
                        InspiratoryTime = sensorData.InspiratoryTimes[i] * 50;
                        ExpiratoryTime = (int)(sensorData.ExpiratoryTimes[i] * tempOffset) * 50;
                    }
                    else
                    {
                        IERate = tempRespiratoryRate;
                        InspiratoryTime = sensorData.InspiratoryTimes[i] * 50;
                        ExpiratoryTime = sensorData.ExpiratoryTimes[i] * 50;
                    }
                    tempRespiratoryRates.Add(RespiratoryRate);
                    RespiratoryRateAve = (int)tempRespiratoryRates.Average();
                    //RespiratoryRateAve = (int)((RespiratoryRateAve * (tempRespiratoryRates.Count - 1) + tempRespiratoryRates[tempRespiratoryRates.Count - 1]) / tempRespiratoryRates.Count);
                    DealBreathe();
                }

                // 若呼吸频率与吸呼比即时值有效且无基值，则将即时值加入基值计算队列
                if (!has_B_Basic)
                {
                    if (RespiratoryRate <= 25 && IERate >= 0.3 && IERate <= 0.7)
                    {
                        respiratoryRates.Add(RespiratoryRate);
                        IERates.Add(IERate);
                        if (pulses_Basic.Count >= (CBCount + 20) && respiratoryRates.Count >= 4)
                        {
                            if (GetBasicValue_Time >= 60000)
                            {
                                GetBasicValue();
                            }
                        }
                    }
                }
                else if (has_H_Basic)
                {

                    Update_B_value(RespiratoryRate - reportData[1][0], reportData[2][0] - IERate);
                }
                tempBreatheID = 11;
            }
        }

        protected void DealBreathe()
        {
            tempIERates.Add(IERate);
        }

        /// <summary>
        /// 临时存储H放松指数
        /// </summary>
        private float temp_H_value = 0f;
        /// <summary>
        /// 更新H放松指数（放松度）
        /// </summary>
        /// <param name="_pulse"></param>
        private void Update_H_value(float _pulse)
        {
            // H放松指数
            float tempHPN = reportData[0][0] - _pulse;
            if (tempHPN >= 0 && tempHPN <= 1)
            {
                tempHPN += 1;
            }
            if (tempHPN >= 0)
            {
                HP_value += tempHPN;
            }
            else
            {
                HN_value -= tempHPN;
            }
            if (HP_value == 0 && HN_value == 0)
            {
                temp_H_value = 0;
            }
            else
            {
                temp_H_value = (HP_value / (HP_value + HN_value)) * 100;
            }
            if (temp_H_value >= 50)
            {
                H_value = (float)(100 - Math.Pow((double)(temp_H_value - 100), 2) / 50);
            }
            else
            {
                H_value = (float)(Math.Pow((double)temp_H_value, 2) / 50);
            }
            Update_C_value();
        }
        private void Update_h_value(float _pulse)
        {
            // H放松指数
            float tempHPN = reportData[0][0] - _pulse;
            if (tempHPN >= 0 && tempHPN <= 1)
            {
                tempHPN += 1;
            }
            if (tempHPN >= 0)
            {
                HP_value += tempHPN;
            }
            else
            {
                HN_value -= tempHPN;
            }
            if (HP_value == 0 && HN_value == 0)
            {
                temp_H_value = 0;
            }
            else
            {
                temp_H_value = (HP_value / (HP_value + HN_value)) * 100;
            }
            if (temp_H_value >= 50)
            {
                h_value = (float)(100 - Math.Pow((double)(temp_H_value - 100), 2) / 50);
            }
            else
            {
                h_value = (float)(Math.Pow((double)temp_H_value, 2) / 50);
            }
            Update_c_value();
        }

        private float temp_BR_value = 0f;
        /// <summary>
        /// 更新B放松指数（专注度）
        /// </summary>
        /// <param name="_respiratoryRate"></param>
        /// <param name="_ieRate"></param>
        private void Update_B_value(float _respiratoryRate, float _ieRate)
        {
            // B放松指数
            for (int i = 0; i < BFC_Table.Length; i++)
            {
                if (_respiratoryRate > BFC_Table[i, 0] && _respiratoryRate <= BFC_Table[i, 1])
                {
                    BFC_fraction[BFID] = (float)BFC_Table[i, 2];
                    break;
                }
            }
            for (int j = 0; j < IERC_Table.Length; j++)
            {
                if (_ieRate > IERC_Table[j, 0] && _ieRate <= IERC_Table[j, 1])
                {
                    IERC_fraction[BFID] = (float)IERC_Table[j, 2];
                    break;
                }
            }
            BFID++;
            if (BFID == 4)
            {
                BRV = 1 - (BFC_fraction.Sum() + IERC_fraction.Sum()) / 16;
                if (BRV > 0)
                {
                    BRPV += BRV;
                    if (consecutiveCountOfBRNV > 0)
                        consecutiveCountOfBRNV = 0;
                }
                else if (BRV < 0)
                {
                    BRNV -= BRV;
                    countOfBRNV++;
                    consecutiveCountOfBRNV++;
                }
                if (BRPV == 0 && BRNV == 0)
                {
                    temp_BR_value = 0;
                }
                else
                {
                    temp_BR_value = (BRPV / (BRPV + BRNV)) * 100;
                }
                if (temp_BR_value >= 50)
                {
                    BR_value = (float)(100 - Math.Pow((double)(temp_BR_value - 100), 2) / 50);
                }
                else
                {
                    BR_value = (float)(Math.Pow((double)temp_BR_value, 2) / 50);
                }
                Update_C_value();
                BFID = 0;
            }
        }
        private void Update_b_value(float _respiratoryRate, float _ieRate)
        {
            // B放松指数
            for (int i = 0; i < BFC_Table.Length; i++)
            {
                if (_respiratoryRate > BFC_Table[i, 0] && _respiratoryRate <= BFC_Table[i, 1])
                {
                    BFC_fraction[BFID] = (float)BFC_Table[i, 2];
                    break;
                }
            }
            for (int j = 0; j < IERC_Table.Length; j++)
            {
                if (_ieRate > IERC_Table[j, 0] && _ieRate <= IERC_Table[j, 1])
                {
                    IERC_fraction[BFID] = (float)IERC_Table[j, 2];
                    break;
                }
            }
            BFID++;
            if (BFID == 4)
            {
                BRV = 1 - (BFC_fraction.Sum() + IERC_fraction.Sum()) / 16;
                if (BRV > 0)
                {
                    BRPV += BRV;
                    if (consecutiveCountOfBRNV > 0)
                        consecutiveCountOfBRNV = 0;
                }
                else if (BRV < 0)
                {
                    BRNV -= BRV;
                    countOfBRNV++;
                    consecutiveCountOfBRNV++;
                }
                if (BRPV == 0 && BRNV == 0)
                {
                    temp_BR_value = 0;
                }
                else
                {
                    temp_BR_value = (BRPV / (BRPV + BRNV)) * 100;
                }
                if (temp_BR_value >= 0.5)
                {
                    br_value = (float)(100 - Math.Pow((double)(temp_BR_value - 100), 2) / 50);
                }
                else
                {
                    br_value = (float)(Math.Pow((double)temp_BR_value, 2) / 50);
                }
                Update_c_value();
                BFID = 0;
            }
        }
        /// <summary>
        /// 更新综合放松指数
        /// </summary>
        private void Update_C_value()
        {
            // 综合放松指数
            C_value = (float)(H_value * 0.6 + BR_value * 0.4);
            tempC_Values.Add(C_value);
            if ((byte)(C_value / 12) != C_Value_Level)
            {
                C_Value_Level = (byte)(C_value / 12 < 0 ? 0 : C_value / 12 > 8 ? 8 : (byte)(C_value / 12));
                sendData[2] = 0x00;
                sendData[6] = (byte)((0x01) + (C_Value_Level << 4));
                SendCommand?.Invoke(this, sendData);
            }
        }

        public event EventHandler<byte[]> SendCommand;

        private void Update_c_value()
        {
            // 综合放松指数
            c_value = (float)(H_value * 0.6 + BR_value * 0.4);
        }

        private bool isMachineWork = false;
        private int countOfMachineNotWork = 0;
        //  bool isPulseWork = false;
        // int countOfPulseNotWork = 0;
        bool isBreatheWork = true;
        // int countOfBreatheNotWork = 0;

        int GetBasicValue_Time = 0;
        public void UpdateData(TimeSpan time)
        {
            // 检测是否有收到传感器信号
            if (isMachineWork)
            {
                isMachineWork = false;
                countOfMachineNotWork = 0;
            }
            else
            {
                countOfMachineNotWork++;
                if (countOfMachineNotWork >= 6)
                {
                    if (MachineSignal)
                    {
                        MachineSignal = false;
                    }
                    if (countOfMachineNotWork >= 1)
                    {
                        countOfMachineNotWork = 0;
                    }
                }
            }

            // 过滤完无效信号
            if (UselessDataCount >= 1)
            {
                if (isBreatheWork)
                {
                    isBreatheWork = false;
                }
                else
                {
                    breatheUnvariedCount++;
                    if (breatheUnvariedCount == 2)
                    {
                        if (BreatheErrorState == ErrorState.Disturb)
                        {
                            _maxAbnormityRespiratoryCount = 0;
                        }
                        else if (BreatheErrorState == ErrorState.None)
                        {
                            if (PulseErrorState == ErrorState.None)
                            {
                                disturbBeginTime = time;
                            }
                        }
                    }
                    else if (breatheUnvariedCount == 4)
                    {
                        BreatheErrorState = ErrorState.Interrupt;
                        if (BreatheSignal)
                            BreatheSignal = false;
                    }
                }

                //开始取基值
                if (GetBasicValue_Time <= 60000)
                {
                    GetBasicValue_Time += 10000;
                }
                // 取完基值
                if (TrainingState == TrainingState.Started)
                {
                    // 计算训练中所需数据
                    GetTrainingData(time);
                }
            }
        }

        bool HasResetMusicPlayer = false;

        private void GetBasicValue()
        {
            float tempPulse_Basic_Value = (float)pulses_Basic.Average();
            if (tempPulse_Basic_Value >= 45 && tempPulse_Basic_Value <= 120)
            {
                Pulse_Basic_Value = reportData[0][0] = tempPulse_Basic_Value;

                _maxPulseCycle = (int)(60000 / (pulse_Basic_Value * 0.8));
                _minPulseCycle = (int)(60000 / (pulse_Basic_Value * 1.1));
                _minAbnormityPulseCycle = (int)(60000 / (pulse_Basic_Value * 1.15));

                has_H_Basic = true;

                foreach (float p in pulses_Basic)
                {
                    Update_h_value(p);
                }

                pulses_Basic.Clear();
                pulses_Basic = null;

                Respiratory_Basic_Value = reportData[1][0] = (float)respiratoryRates.Average();
                IERate_Basic_Value = reportData[2][0] = (float)IERates.Average();

                _maxAbnormityRepiratory = 35;

                has_B_Basic = true;

                for (int i = 0; i < respiratoryRates.Count; i++)
                {
                    Update_b_value(respiratoryRates[i], IERates[i]);
                }

                Update_C_value();

                respiratoryRates.Clear();
                respiratoryRates = null;
                IERates.Clear();
                IERates = null;

                DealBasicValue();

                // H/B/C放松指数基值
                reportData[3][0] = H_value;
                reportData[4][0] = BR_value;
                reportData[5][0] = C_value;

                // 清空干扰时间
                disturbBeginTime = disturbEndTime = TimeSpan.Zero;
                DisturbTime = new TimeSpan(0, 0, 0);

                // 开始进入训练状态
                TrainingState = TrainingState.Started;
            }
        }

        /// <summary>
        /// 有效脉搏周期上限
        /// </summary>
        private int _maxPulseCycle;
        /// <summary>
        /// 有效脉搏周期下限
        /// </summary>
        private int _minPulseCycle;
        /// <summary>
        /// 异常脉搏周期下限
        /// </summary>
        private int _minAbnormityPulseCycle;
        /// <summary>
        /// 异常脉搏周期数
        /// </summary>
        private int _minAbnormityPulseCycleCount;

        /// <summary>
        /// 异常呼吸周期上限
        /// </summary>
        private int _maxAbnormityRepiratory = 0;
        /// <summary>
        /// 异常呼吸周期数
        /// </summary>
        private int _maxAbnormityRespiratoryCount;
        /// <summary>
        /// 取初标
        /// </summary>
        /// <param name="_souce"></param>
        private int GetAverageData(List<float> _souce)
        {
            float _pulse = _souce.Average();
            float _maxPulse = _pulse * 1.1f;
            float _minPulse = _pulse * 0.8f;
            bool continueGetData = false;
            for (int i = 0; i < _souce.Count; i++)
            {
                if (_souce[i] < _minPulse || _souce[i] > _maxPulse)
                {
                    _souce.RemoveAt(i);
                    if (!continueGetData)
                        continueGetData = true;
                    --i;
                }
            }
            if (continueGetData)
            {
                GetAverageData(_souce);
            }
            if (_souce.Count > 0)
            {
                _minPulseCycle = (int)(60000 / _maxPulse);
                _maxPulseCycle = (int)(60000 / _minPulse);
            }
            return _souce.Count;
        }

        protected void DealBasicValue()
        {
        }

        protected void GetTrainingData(TimeSpan time)
        {
            if (pulseErrorState != ErrorState.Interrupt)
            {
                H_values.Add(H_value);
            }
            else
            {
                H_values.Add(float.NaN);
            }
            if (breatheErrorState != ErrorState.Interrupt)
            {
                B_values.Add(BR_value);
            }
            else
            {
                B_values.Add(float.NaN);
            }

            int currentMinuteCount = time.Minutes;
            if (currentMinuteCount >= C_values.Count)
            {
                if (pulseCycles.Count > 0)
                {
                    float tempPulseCycle = pulseCycles.Average();
                    _minPulseCycle = (int)(tempPulseCycle / 1.1);
                    _maxPulseCycle = (int)(tempPulseCycle / 0.8);
                }

                if (tempC_Values.Count > 0)
                {
                    float tempC_Value = tempC_Values.Average();
                    tempC_Values.Clear();
                    C_values.Add(tempC_Value);
                    if (Max_C_Value < tempC_Value)
                    {
                        Max_C_Value = tempC_Value;
                    }
                    C_ValueAveInOneMinute = tempC_Value;

                    if (C_values.Count == 1)
                    {
                        Min_C_Value = c_ValueAveInOneMinute;
                    }
                    else
                    {
                        if (Min_C_Value > c_ValueAveInOneMinute)
                        {
                            Min_C_Value = c_ValueAveInOneMinute;
                        }
                    }
                }
                else
                {
                    C_values.Add(float.NaN);
                    C_ValueAveInOneMinute = 0f;
                }
            }
        }

        public object _lock = new object();

        /// <summary>
        /// 初始化播放器
        /// </summary>
        /// <param name="_start">要初始化的状态</param>
        public void Reset(bool _start)
        {
            if (_start)
            {
                sendData[2] = 0x00;
                sendData[6] = (byte)((0x01) + (C_Value_Level << 4));
                SendCommand.Invoke(this, sendData);
            }
            else
            {
                if (!IsMP3State)
                {
                    // 回MP3状态
                    sendData[2] = 0x0F;
                    sendData[6] = 0x00;
                    SendCommand.Invoke(this, sendData);
                }
            }
        }

        public void UnBind()
        {
            sendData[2] = 0x0F;
            sendData[6] = 0x00;
            SendCommand.Invoke(this,sendData);
        }

        /// <summary>
        /// 开始训练
        /// </summary>
        public void StartTraining()
        {
        }

        /// <summary>
        /// 结束训练
        /// </summary>
        public void QuitTraining()
        {
            Reset(false);

            TrainingState = TrainingState.QuitTraining;
        }

        public void StopTraining()
        {
            Reset(false);

            tempPulses = tempPulses.Where(value => !float.IsInfinity(value) && !float.IsNaN(value)).ToList();
            tempRespiratoryRates = tempRespiratoryRates.Where(value => !float.IsInfinity(value) && !float.IsNaN(value)).ToList();
            tempIERates = tempIERates.Where(value => !float.IsInfinity(value) && !float.IsNaN(value)).ToList();
            H_values = H_values.Where(value => !float.IsInfinity(value) && !float.IsNaN(value)).ToList();
            B_values = B_values.Where(value => !float.IsInfinity(value) && !float.IsNaN(value)).ToList();
            C_values = C_values.Where(value => !float.IsInfinity(value) && !float.IsNaN(value)).ToList();
            GetAverageData(ref reportData[0], tempPulses, true);
            GetAverageData(ref reportData[1], tempRespiratoryRates, true);
            GetAverageData(ref reportData[2], tempIERates, true);
            GetAverageData(ref reportData[3], H_values, true);
            GetAverageData(ref reportData[4], B_values, true);
            GetAverageData(ref reportData[5], C_values, true);

            Max_H_Value = H_values.Count > 0 ? H_values.Max() : 0;
            Min_H_Value = H_values.Count > 0 ? H_values.Where(value => !value.Equals(float.NaN)).Min() : 0;
            Max_B_Value = B_values.Count > 0 ? B_values.Max() : 0;
            Min_B_Value = B_values.Count > 0 ? B_values.Where(value => !value.Equals(float.NaN)).Min() : 0;
            TrainingState = TrainingState.TrainingEnd;
        }


        #region 计算平均值
        public static void GetAverageData(ref float[] _returnValue, List<float> _sourceValue, bool hasNaNValue)
        {
            if (hasNaNValue)
            {
                _sourceValue = _sourceValue.Where(value => !value.Equals(float.NaN)).ToList();
            }
            if (_sourceValue.Count > 0)
            {
                if (_sourceValue.Count <= 3)
                {
                    _returnValue[1] = _sourceValue[0];
                    _returnValue[2] = _sourceValue.Count > 1 ? _sourceValue[1] : 0;
                    _returnValue[3] = _sourceValue.Count > 2 ? _sourceValue[2] : 0;
                }
                else
                {
                    float[] tempValues = new float[_sourceValue.Count / 3];
                    _sourceValue.CopyTo(0, tempValues, 0, tempValues.Length);
                    _returnValue[1] = tempValues.Average();
                    _sourceValue.CopyTo(tempValues.Length, tempValues, 0, tempValues.Length);
                    _returnValue[2] = tempValues.Average();
                    _sourceValue.CopyTo(tempValues.Length * 2, tempValues, 0, tempValues.Length);
                    _returnValue[3] = tempValues.Average();
                }
                _returnValue[4] = (_returnValue[1] + _returnValue[2] + _returnValue[3]) / 3;
                float _tempReturnValue_4 = _returnValue[4];
                _returnValue[5] = (float)Math.Sqrt(_sourceValue.Average((_s) => Math.Pow((double)(_s - _tempReturnValue_4), 2)));
            }
            else
            {
                _returnValue[1] = _returnValue[2] = _returnValue[3] = _returnValue[4] = _returnValue[5] = 0;
            }
        }

        #endregion 计算平均值

        internal ChengYuanTrainingRec Save()
        {
            if (TrainingState == TrainingState.TrainingEnd)
            {
                ChengYuanTrainingRec rec = new ChengYuanTrainingRec();
                rec.ChengYuanID = ChengYuanInfo.Id;
                rec.Code = ChengYuanInfo.Code;
                rec.TotalR = Math.Round(reportData[3][4], 2);
                rec.TotalC = Math.Round(reportData[4][4], 2);
                rec.TotalRC = Math.Round(reportData[5][4], 2);

                return rec;
            }

            return null;
        }

        #region INotifyPropertyChanged 成员
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}
